import React from 'react'
import { Breadcrumb } from 'antd';
import { Button, Checkbox, Form, Input } from 'antd';
import { useEffect, useState } from 'react';
import { Col, Row } from 'antd';
import { DownloadOutlined, SettingOutlined, EyeOutlined, SkinOutlined, PhoneOutlined, StarOutlined, MailOutlined, HomeOutlined } from '@ant-design/icons';
// import { Button, Modal } from 'antd';
import { Radio } from 'antd';
import { DownOutlined, UserOutlined, SmileOutlined, ClockCircleOutlined, LoginOutlined, BankOutlined } from '@ant-design/icons';
import { Dropdown, message, Space, Tooltip } from 'antd';
import { Table, Tag } from 'antd';
import api from '../../aips/user'
import { Divider } from 'antd';
import { Modal } from 'antd';
import '../../assets/styles/center.css'
import { NoStyleItemContext } from 'antd/lib/form/context';
import { PlusOutlined } from '@ant-design/icons';
import { Select, Cascader, DatePicker, InputNumber, TreeSelect, Switch, Upload, } from 'antd';
import userApi from '../../aips/user';
import { Drawer } from 'antd';
import { useRef } from 'react';
import { Pagination } from 'antd';
import Bread from '../../components/breadcrumb/Bread';
import password from '../../aips/password';
import excel from '../../aips/excel'
const { RangePicker } = DatePicker;
const { TextArea } = Input;

const showTotal = (total) => `共 ${total} 条数据`;
const formItemLayout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 16,
  },
};
const formTailLayout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
    offset: 20,
  },
}

const User = () => {
  const [size, setSize] = useState('large');
  const [form] = Form.useForm();
  const [checkNick, setCheckNick] = useState(false);
  useEffect(() => {
    form.validateFields(['nickname']);
  }, [checkNick, form]);
  const onCheckboxChange = (e) => {
    setCheckNick(e.target.checked);
  };
  const [totals, setTotals] = useState(10)

  useEffect(() => {
    addlist()
  }, [])
  const [pageSize, setPageSize] = useState('10')
  const [pageNum, setPageNum] = useState('1')
  const [sortField, setSortField] = useState('')
  const [sortOrder, setSortOrder] = useState('')
  const [createTimeFrom, setCreateTimeFrom] = useState('')
  const [createTimeTo, setCreateTimeTo] = useState('')
  const [username, setUsername] = useState('')
  const [deptId, setDeptId] = useState('')
  async function addlist() {
    const res = await api.user({ pageSize, pageNum, sortField, sortOrder, createTimeFrom, createTimeTo, username, deptId, })
    setData([...res.rows])
    setTotals(res.total)
  }
  const handleMenuClick = (e) => {
    if (e.key == '1') {
      if (userpassword.length > 0) {
        showModal()
      } else {
        message.error('请选择需要重置密码的用户')
      }

      // 密码重置
    } else {
      // 到处Excel
      excel.excel({}).then(res => {
        console.log(res);
      })
    }
  };
  const items = [
    {
      label: '密码重置',
      key: '1',

    },
    {
      label: '导出Excel',
      key: '2',
    },

  ];
  const menuProps = {
    items,
    onClick: handleMenuClick,
  };

  const [data, setData] = useState([])


  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const handleChange = (pagination, filters, sorter) => {
    setPageNum(pagination.current)
    setPageSize(pagination.pageSize)
    addlist()
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

  const columns = [

    {
      title: '用户名',
      dataIndex: 'username',
      sorter: (a, b) => a.username.length - b.username.length,
      sortOrder: sortedInfo.field === 'username' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      render: (_, record) => {
        if (record.ssex == '0') {
          return '男'
        } else if (record.ssex == '2') {
          return '女'
        } else {
          return '保密'
        }
      },

      filters: [
        {
          text: '男',
          value: '0',
        },
        {
          text: '女',
          value: '2',
        },
      ],
      filteredValue: filteredInfo.ssex || null,
      onFilter: (value, record) => record.ssex == value,
      ellipsis: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => {
        if (record.status == '0') {
          return <Tag color={'volcano'} key={record.userId}>
            锁定</Tag>
        } else {
          return <Tag color={'green'} key={record.userId}>
            有效</Tag>
        }
      },
      filters: [
        {
          text: '锁定',
          value: '0',
        },
        {
          text: '有效',
          value: '1',
        },
      ],
      filteredValue: filteredInfo.status || null,
      onFilter: (value, record) => record.status == value,
      sorter: (a, b) => a.address.length - b.address.length,
      sortOrder: sortedInfo.field === 'address' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a, b) => a.createTime > b.createTime,
      sortOrder: sortedInfo.field === 'createTime' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: '',
      render: (_, record) => <i><SettingOutlined style={{ color: '#1189FE' }} onClick={() =>
        adduser(record)
      }
      /><EyeOutlined style={{ color: 'rgb(66, 185, 131)', marginLeft: '20px' }} onClick={() =>
        nextArr(record)}
        /></i>
    },
  ];
  const [usernext, setUsernext] = useState({})
  function nextArr(e) {
    setUsernext(e)
    setModal2Open(true)
  }

  const refs = useRef([])//ref的第三点作用是：
  const objs = {}
  function adduser(e) {
    setUsernext(e)
    setModal1Open(true)
  }
  const [selectionType, setSelectionType] = useState('checkbox');
  const [userpassword, setUserpassword] = useState([]);
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(selectedRows);
      serUserId(selectedRowKeys)
      setUserpassword(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  const [componentDisabled, setComponentDisabled] = useState(false);
  const onFormLayoutChange = ({ disabled }) => {
    setComponentDisabled(disabled);
  };


  // 修改
  const [modal1Open, setModal1Open] = useState(false);
  const [modal2Open, setModal2Open] = useState(false);
  const onFinish = (values) => {
    console.log('Success:', values);
    userApi.adduser({
      ...values,
      userId: usernext.userId
    }).then(res => {
      message.success('修改成功')
      addlist()
      setModal1Open(false)
      setUsernext({})
      console.log(usernext);
    })
  };

  const onFinishFailed = (errorInfo) => {
    setUsernext({})
    console.log(usernext);
  };
  // 新增
  const onFinish1 = (values) => {
    console.log('Success:', values);
    api.userobj({ ...values }).then(res => {
      message.success('添加成功')
      onClose()
    })
  };

  const onFinishFailed1 = (errorInfo) => {
  };



  const [open, setOpen] = useState(false);
  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  // 删除
  const [userId, serUserId] = useState('')
  function handeldeleteuser() {
    if (userId) {

      api.delete(userId).then(res => {
        console.log(res);
        addlist()
        message.success('删除成功')
      })
    } else {
      message.error('删除失败')
    }
  }
  const onFinish3 = (values) => {

    setUsername('')
    setDeptId('')
    setCreateTimeFrom('')
    setCreateTimeTo('')
    console.log('Success:', values);
    if (values.username) {
      setUsername(values.username)
    }
    if (values.deptId) {
      setDeptId(values.deptId)
    }
    if (values.createTimeFrom) {
      setCreateTimeFrom(values.createTimeFrom[0].format('YYYY-MM-DD'))
    }
    if (values.createTimeFrom) {
      setCreateTimeTo(values.createTimeFrom[1].format('YYYY-MM-DD'))
    }
    addlist()
  }
  const onFinishFailed3 = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const onReset = () => {
    form.resetFields();
  };
  function showSizeChanger() {

  }
  function showQuickJumper() {

  }


  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    password.poms({ usernames: userpassword[0].username }).then(res => {
      message.success('密码重置成功')
    
    })
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div>
      <div style={{ margin: '5px 0px 30px 0px' }}>
        <Bread></Bread>
      </div>
      <Form form={form} name="dynamic_rule"
        onFinish={onFinish3}
        onFinishFailed={onFinishFailed3}
      >
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="username"
              label="用户名："


            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>

            <Form.Item
              {...formItemLayout}
              name="deptId"
              label="部门："

            >
              <Input />
            </Form.Item>
          </Col>

        </Row>
        <Row>
          <Col span={12}>
            <Form.Item name="createTimeFrom" label="创建时间"
              style={{ marginLeft: '32px' }}
            >
              <RangePicker style={{ width: '408px' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="" onClick={onReset}>
                重置
              </Button>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div>
        <Radio.Group value={size} onChange={(e) => setSize(e.target.value)}>
          <Radio.Button value="large" onClick={showDrawer}>新增</Radio.Button>
          <Radio.Button value="default" style={{ margin: '10px' }} onClick={handeldeleteuser}>删除</Radio.Button>
          <Dropdown menu={menuProps}>
            <Button>
              <Space>
                更多操作
                <DownOutlined />
              </Space>
            </Button>
          </Dropdown>
        </Radio.Group>
      </div>
      <>

        <Divider />
        <Table
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }}
          columns={columns} dataSource={data} onChange={handleChange} rowKey="userId"
          pagination={{ total: totals, showSizeChanger, showQuickJumper, showTotal, pageSizeOptions: [2, 5, 10] }}
        />
        {/* <Pagination size="small" total={50} showSizeChanger showQuickJumper /> */}
      </>
      <>
        <Modal
          maskClosable={false}
          title="修改用户"
          style={{ top: 0, marginLeft: '100%', height: '100' }}
          visible={modal1Open}
          onOk={() => setModal1Open(false)}
          onCancel={() => setModal1Open(false)}
          width='600px'
          closable={false}
          footer={null}
          bodyStyle={{ height: 'calc(100vh - 80px)' }}
        >
          <div>
            <>
              <Form
                labelCol={{
                  span: 4,
                }}
                wrapperCol={{
                  span: 14,
                }}
                initialValues={usernext}
                layout="horizontal"
                onValuesChange={onFormLayoutChange}
                disabled={componentDisabled}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
              >
                <Form.Item label="用户名" name='username'
                >
                  <Input />
                </Form.Item>
                <Form.Item label="邮箱" name='email'>
                  <Input />
                </Form.Item>
                <Form.Item label="手机" name='mobile'>
                  <Input />
                </Form.Item>


                <Form.Item label="角色"
                  name="roleId"
                  rules={[
                    {
                      required: true,
                      message: '请选择角色'
                    },
                  ]}
                >
                  <Select
                  >
                    <Select.Option value="1">管理员</Select.Option>
                    <Select.Option value="2">注册用户</Select.Option>
                    <Select.Option value="3">普通用户</Select.Option>
                    <Select.Option value="4">商家</Select.Option>
                    <Select.Option value="5">绿钻会员</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item label="部门" name='deptId'>
                  <TreeSelect

                    treeData={[
                      {
                        title: '开发部',
                        value: '1',
                      },
                      {
                        title: '市场部',
                        value: '2',
                      },
                      {
                        title: '人事部',
                        value: '3',
                      },
                      {
                        title: '测试部',
                        value: '4',
                      },
                    ]}
                  />
                </Form.Item>
                <Form.Item label="状态"
                  name='status'
                  rules={[
                    {
                      required: true,
                      message: '请选择状态'
                    },
                  ]}>
                  <Radio.Group>
                    <Radio value="1"> 有效 </Radio>
                    <Radio value="0"> 锁定 </Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item label="性别" name='ssex'
                  rules={[
                    {
                      required: true,
                      message: '请选择性别'
                    },
                  ]}>
                  <Radio.Group>
                    <Radio value="0"> 男 </Radio>
                    <Radio value="1"> 女 </Radio>
                    <Radio value="2"> 保密 </Radio>
                  </Radio.Group>
                </Form.Item>

                <Form.Item label="Button" >
                  <Button type="primary" htmlType="submit">
                    确认
                  </Button>
                </Form.Item>
              </Form>
            </>
          </div>

        </Modal>
        <br />
        <br />
        <Modal
          title="用户信息"
          maskClosable={false}
          visible={modal2Open}
          onOk={() => setModal2Open(false)}
          onCancel={() => setModal2Open(false)}
          width='750px'
          bodyStyle={{ height: '300px' }}
          footer={null}
        >
          <div className='f-c-c' style={{ width: '100%', height: '100%', }}>
            <div style={{ width: '200px', height: '100%' }} className='f-c-c'>
              <img src={`http://xawn.f3322.net:8002/distremote/static/avatar/${usernext.avatar}`}
                style={{ width: '160px', height: '160px', borderRadius: '50%' }} alt="" />
            </div>
            <div style={{ width: '550px', height: '100%' }} className='f-c-c'>
              <div style={{ width: '50%', height: '100%' }}>
                <div className='f-c-s'><UserOutlined className='mar' /><span>账户：{usernext.username}</span></div>
                <div className='f-c-s'><StarOutlined className='mar' /><span>角色：{usernext.roleName}</span></div>
                <div className='f-c-s'><SkinOutlined className='mar' /><span>性别：{usernext.ssex}</span></div>
                <div className='f-c-s'><PhoneOutlined className='mar' /><span>电话：{usernext.mobile}</span></div>
                <div className='f-c-s'><MailOutlined className='mar' /><span>邮箱：{usernext.email}</span></div>
              </div>
              <div style={{ width: '50%', height: '100%' }}>
                <div className='f-c-s'><HomeOutlined className='mar' /><span>部门：{usernext.deptName}</span></div>
                <div className='f-c-s'><SmileOutlined className='mar' /><span>状态：{usernext.status}</span></div>
                <div className='f-c-s'><ClockCircleOutlined className='mar' /><span>创建时间：{usernext.createTime}</span></div>
                <div className='f-c-s'><LoginOutlined className='mar' /><span>最近登录：{usernext.lastLoginTime}</span></div>
                <div className='f-c-s'><BankOutlined className='mar' /><span>描述：{usernext.description}</span></div>
              </div>
            </div>
          </div>
        </Modal>
      </>

      <>

        <Drawer title="新增用户" placement="right" open={open}
          width={500} closeIcon='' maskClosable={false}
        >
          <>
            <Form
              labelCol={{
                span: 4,
              }}
              wrapperCol={{

              }}
              layout="horizontal"
              onValuesChange={onFormLayoutChange}
              disabled={componentDisabled}
              onFinish={onFinish1}
              onFinishFailed={onFinishFailed1}
            >
              <Form.Item label="用户名" name='username'
                rules={[
                  {
                    required: true,
                    message: '请选择用户名'
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item label="密码" name='password'
                rules={[
                  {
                    required: true,
                    message: '请输入密码'
                  },
                ]}
              >
                <Input type='password' />
              </Form.Item>
              <Form.Item label="邮箱" name='email'
                rules={[
                  {
                    required: true,
                    message: '请选择邮箱'
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item label="手机" name='mobile'
                rules={[
                  {
                    required: true,
                    message: '请输入手机号'
                  },
                ]}>
                <Input />
              </Form.Item>


              <Form.Item label="角色"
                name="roleId"
                rules={[
                  {
                    required: true,
                    message: '请选择角色'
                  },
                ]}
              >
                <Select
                >
                  <Select.Option value="1">管理员</Select.Option>
                  <Select.Option value="2">注册用户</Select.Option>
                  <Select.Option value="3">普通用户</Select.Option>
                  <Select.Option value="4">商家</Select.Option>
                  <Select.Option value="5">绿钻会员</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="部门" name='deptId'
                rules={[
                  {
                    required: true,
                    message: '请选择部门'
                  },
                ]}>
                <TreeSelect

                  treeData={[
                    {
                      title: '开发部',
                      value: '1',
                    },
                    {
                      title: '市场部',
                      value: '2',
                    },
                    {
                      title: '人事部',
                      value: '3',
                    },
                    {
                      title: '测试部',
                      value: '4',
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item label="状态"
                name='status'
                rules={[
                  {
                    required: true,
                    message: '请选择状态'
                  },
                ]}>
                <Radio.Group>
                  <Radio value="1"> 有效 </Radio>
                  <Radio value="0"> 锁定 </Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item label="性别" name='ssex'
                rules={[
                  {
                    required: true,
                    message: '请选择性别'
                  },
                ]}>
                <Radio.Group>
                  <Radio value="0"> 男 </Radio>
                  <Radio value="1"> 女 </Radio>
                  <Radio value="2"> 保密 </Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item label="" style={{ marginTop: '80px' }}>
                <hr />
                <Row>
                  <Col span={16}>
                  </Col>
                  <Col span={8}>
                    <Button style={{ marginRight: 10 }} onClick={onClose}>
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">确认</Button>
                  </Col>
                </Row>


              </Form.Item>
            </Form>
          </>
        </Drawer>
      </>
      <>
        {/* 重置密码模态框 */}
        <Modal title="确定重置选中用户密码？" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} maskClosable={false}>
          <p>当您点击确定按钮后，这些用户的密码将会重置为1234qwer</p>
        </Modal>
      </>
    </div>
  )
}

export default User